#include "face_collect_face_data.h"

Face_Collect_Face_Data::Face_Collect_Face_Data(QWidget *parent)
    : CommonGraphicsView{parent}
{
    this->setWindowTitle("采集人脸数据");
    QPushButton *btn = new QPushButton(this);
    btn->setText("选择视频文件采集人脸数据");
    connect(btn,&QPushButton::clicked,[=](){
        chooseVideo();
    });
}

void Face_Collect_Face_Data::chooseVideo(){
    QString filePath = QFileDialog::getOpenFileName(this,"选择视频文件","/Users/yangwei/Downloads/","数据文件(*.mp4)");
    qDebug()<<filePath;
    saveCollectFaceData(filePath.toStdString().c_str());
}


void Face_Collect_Face_Data::saveCollectFaceData(const char * filePath){
    //级联分类器文件路径
    string haarFilePath = "/usr/local/share/opencv4/haarcascades/haarcascade_frontalface_alt_tree.xml";
    VideoCapture capture;
    capture.open(filePath);
    if(!capture.isOpened()){
        qDebug()<<"无法打开视频文件";
        return;
    }

    CascadeClassifier faceDetector;//实例化级联分类器
    faceDetector.load(haarFilePath);

    Mat frame;
    vector<Rect> faces;
    int count = 0;
    while(capture.read(frame)){
        faceDetector.detectMultiScale(frame,faces,1.1,3,0,Size(100,100),Size(400,400));
        for(int i=0;i<faces.size();i++){
            //将识别到的人脸区域存储起来
            if(count%10==0){
                Mat result;
                cv::resize(frame(faces[i]),result,Size(100,100));
                String path = format("/Users/yangwei/Documents/tony/opencv/myfaces/face_%d.jpg", count);
                cout << path<<endl;
                imwrite(path, result);
            }
            //将识别到的人脸框绘制出来
            rectangle(frame,faces[i],Scalar(255,0,0),3,8);
        }
        imshow("frame",frame);
        int key = waitKey(1);
        if(key==27){
            break;
        }
        count ++;
    }
}
